package cn.dfun.demo.scdemo.ali.seata.service.impl;

import cn.dfun.demo.scdemo.ali.seata.dao.OrderDao;
import cn.dfun.demo.scdemo.ali.seata.domain.Order;
import cn.dfun.demo.scdemo.ali.seata.service.AccountService;
import cn.dfun.demo.scdemo.ali.seata.service.OrderService;
import cn.dfun.demo.scdemo.ali.seata.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;
    @Resource
    private StorageService storageService;
    @Resource
    private AccountService accountService;

    @Override
    // 添加GlobalTransactional注解进行全局异常处理, name自定义
    @GlobalTransactional(name="fsp-create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("------->开始新建订单");
        orderDao.create(order);

        log.info("------->开始微服务扣减库存");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("------->结束微服务扣减库存");

        log.info("------->开始微服务扣减余额");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("------->结束微服务扣减余额");

        log.info("------->开始修改订单状态");
        orderDao.update(order.getUserId(), 0);
        log.info("------->结束修改订单状态");

        log.info("------->下订单结束");
    }
}
